package com.bhs.auth.service;

import com.bhs.auth.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private RemoteUserService remoteUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        com.bhs.auth.pojo.User user = remoteUserService.selectUserByUsername(username);
        if (user==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        List<String> permissions = remoteUserService.selectUserPermissions(user.getId());
        org.springframework.security.core.userdetails.User userInfo =
                new org.springframework.security.core.userdetails.User(username,
                        user.getPassword(),
                        AuthorityUtils.createAuthorityList(permissions.toArray(new String[]{})));

        return userInfo;
    }
}
